<?php

class Quad_Form extends Quad_Html_Element {

	public $elements;
	public $_attributes = array('action'=>'','method'=>'get');
	protected $_elementClassAliases = array(
		'checkboxes' => 'CheckboxGroup',
		'radios' => 'RadiosGroup'
	);
	
	public function __construct($attributes = array()) {
		parent::__construct('form');
		$this->elements = new Quad_Form_Elements($this);
		$this->setAttributes($attributes);
		$this->addClassName('q-form');
	}
	
	public function addElement($class, $name, $labelText=null, $value=null) {
		if (strpos($class, '_') === false) {
			if (isset($this->_elementClassAliases[$class])) {
				$class = $this->_elementClassAliases[$class];
			}
			$class = "Quad_Form_Element_" . ucwords($class);
		}
		if (!class_exists($class, true)) {
			throw new Quad_Form_Exception("Unknown element type '$type'");
		}
		$this->elements->$name = new $class($labelText, $value);
		return $this;
	}
	
	public function populate($values) {
		
	}
	
	public function isValid() {
		
	}
	
	public function getErrorMessages() {
		
	}
		
	public function setErrorDecorator($decName) {
		
	}
	
	public function __set($p, $v) {
		if ($v instanceof Quad_Form_Element) {
			$this->elements->$p = $v;
			if (!$v->name) {
				$v->name = $p;
			}
			if (!$v->id) {
				$v->id = $p;
			}
			$v->form = $this;
		}
		parent::__set($p,$v);
	}
	
	public function __get($p) {
		if ($this->elements->$p instanceof Quad_Form_Element) {
			return $this->elements->$p;
		}
		if ($p == 'length') {
			return count($this->elements);
		}
		return parent::__get($p);
	}
	
	public function getElementsHtml() {
		// add this class's error decorator to each element, render elements, then remove that decorator
		$out = "\n";
		foreach ($this->elements as $el) {
			$out .= $el . "\n";
		}
		return $out;
	}
	
	public function __toString() {
		$html = '';
		$html .= $this->getOpenTag();
		//$dec = new Quad_Form_Layout_Dl($this);
		$dec = new Quad_Form_Layout_Table($this);
		$html .= $dec->render();
		//$html .= $this->getElementsHtml();
		$html .= $this->getCloseTag();
		return $html;
	}
    
}

